<template>
    <div>
      <div class="mt10 whiteBac p10"><el-button size="small" type="primary" @click="publishItem">发布</el-button></div>
      <div class="mt20">
        <el-tabs type="border-card" v-model="activeName" @tab-click="handleTabClick">
          <el-tab-pane label="已发布的推送" name="pushed">
            <div class="a-box-style" v-for="item in pushedData">
              <div>
                <el-row>
                  <el-col :xs="12" :sm="12" :md="12" :lg="12" :xl="12">
                    <div class="fl ag-header">
                      <div class="s-img"><img :src="item.head_url" alt=""></div>
                    </div>
                    <div class="mt5 fl">
                      <div v-for="isNum in isAgent">
                        <span v-if="isNum.agent_num===item.agent_num">{{isNum.name}}</span>
                      </div>
                      <p class="mt10 fs12 light-grey">{{item.create_time}}</p>
                    </div>
                    <div class="clear"></div>
                  </el-col>
                  <el-col :xs="12" :sm="12" :md="12" :lg="12" :xl="12">
                    <div class="tr mt10"><el-button v-if="item.status==='1'" size="small" type="danger" @click="delExtension(item.id)">删除</el-button></div>
                  </el-col>
                </el-row>
              </div>
              <div class="mt15 break lh20">{{item.content}}
                <a :href="item.link_info" v-if="item.link_type==='0'" target="_blank" class="blue-color">网页链接</a>
                <router-link v-if="item.link_type==='1'" class="blue-color" :to="{ name: 'shoppingView',query:{goodsSerialNumber:item.link_info}}">商品链接</router-link>
              </div>
              <div class="a-inline-img mt10" >
                <a v-for="image in item.imgList" target="_blank" :href="image.url"><img :src="image.thumbnail_url" alt=""></a>
              </div>
            </div>
          </el-tab-pane>
          <el-tab-pane label="已删除的推送" name="deleted">
            <div class="a-box-style" v-for="item in deletedData">
              <div>
                <el-row>
                  <el-col :span="12">
                    <el-row>
                      <div class="fl ag-header">
                        <div class="s-img"><img :src="item.head_url" alt=""></div>
                      </div>
                      <div class="mt5 fl">
                        <div v-for="isNum in isAgent">
                          <span v-if="isNum.agent_num===item.agent_num">{{isNum.name}}</span>
                        </div>
                        <p class="mt10 fs12 light-grey">{{item.create_time}}</p>
                      </div>
                      <div class="clear"></div>
                    </el-row>
                  </el-col>
                </el-row>
              </div>
              <div class="mt15 break lh20">{{item.content}}
                <a :href="item.link_info" v-if="item.link_type==='0'" target="_blank" class="blue-color">网页链接</a>
                <router-link v-if="item.link_type==='1'" class="blue-color" :to="{ name: 'shoppingView',query:{goodsSerialNumber:item.link_info}}">商品链接</router-link>
              </div>
              <div class="a-inline-img mt10" >
                <a v-for="image in item.imgList" target="_blank" :href="image.url"><img :src="image.thumbnail_url" alt=""></a>
              </div>
            </div>
          </el-tab-pane>
          <div class="mt10 tc">
            <page-pagination :page="page" :pageSize="pageSize" :total="total" v-on:pageFun="handleCurrentChange"></page-pagination>
          </div>
        </el-tabs>
      </div>

      <!--发布弹窗 begin-->
      <el-dialog width="600px" title="发布推送" :visible.sync="dialogFormVisible">
        <el-form :model="publishForm" :rules="rules" ref="publishForm" label-width="80px" label-position="left">
          <el-form-item label="推送内容" prop="desc">
            <el-input :rows="4" type="textarea" v-model="publishForm.desc"></el-input>
          </el-form-item>
          <el-form-item label="特殊资源" prop="linkType">
            <el-radio-group v-model="publishForm.linkType" size="medium" @change="changeRadioType">
              <el-radio border label="" name="linkType">无</el-radio>
              <el-radio border label="0" name="linkType">超链接</el-radio>
              <el-radio border label="1" name="linkType">商品ID</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="" prop="link">
            <el-input v-model="publishForm.link" :disabled="isDisabledType"></el-input>
          </el-form-item>
          <el-form-item label="图片" style="margin-left: 8px;">
            <el-upload
              ref="upload"
              :limit="publishForm.limitImg"
              :action="uploadFileAction"
              list-type="picture-card"
              accept="image/gif,image/jpeg,image/jpg,image/bmp,image/png"
              :on-preview="handlePictureCardPreview"
              :before-upload="beforeAvatarUpload"
              :on-success="handlePictureCardSuccess"
              :on-remove="handleRemove">
              <i class="el-icon-plus"></i>
            </el-upload>
            <el-dialog v-show="publishForm.isShowAdd" :visible.sync="publishForm.dialogVisibleImg">
              <img width="100%" :src="publishForm.extensionImg" alt="">
            </el-dialog>
            <div class="light-grey fs12 mt10">您最多可以发布6张图片，单张最小200Kb，最大5M</div>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button size="small" @click="dialogFormVisible = false">取 消</el-button>
          <el-button size="small" type="primary" :disabled="isSubmitPush" @click="publishExtension('publishForm')">确 定</el-button>
        </div>
      </el-dialog>
      <!--发布弹窗 end-->
    </div>
</template>

<script>
  import service from '@/service/index'
  import { getCookie } from '@/base/utils'
  import pagePagination from '@/components/AG_Common/pagePagination.vue'
    export default {
      data(){
        return{
          total:0,
          pageSize:10,
          page:1,
          activeName:'pushed',
          tabType:'1',
          pushedData:[],
          deletedData:[],
          dialogFormVisible:false,
          isDisabledType:true,
          isSubmitPush:false,   //发布推送按钮重复提交
          isAgent:getCookie("agentList")||[],
          uploadFileAction:service.haiBeiServerUpload(),
          publishForm:{
            desc:'',
            linkType:'',
            link:'',
            extensionImg:'',
            dialogVisibleImg:false,
            limitImg:6,
            isShowAdd:true
          },
          imageListStr:[],
          thumbUrlStr:[],
          rules:{
            desc:[
              { required: true, message: '请输入推送内容', trigger: 'blur' },
              { min: 1, max: 140, message: '长度在 1 到 140 个字符', trigger: 'blur' }
            ],
            //linkType:[
              //{ required: true, message: '请选择链接类型', trigger: 'change' }
            //],
            //link:[
              //{ required: true, message: '请输入相应类型的链接', trigger: 'blur' },
              //{ min: 1, max: 100, message: '长度在 3 到 5 个字符', trigger: 'blur' }
            //]
          }
        }
      },
      mounted() {
        this.getPushData('1',1);
      },
      components:{
        pagePagination
      },
      methods:{
        handleTabClick(tab, event){
          //console.log(tab.index);
          this.tabType = (tab.index==0)?'1':'0';
          this.getPushData(this.tabType,1);
        },
        handleCurrentChange(val){
          if(this.tabType==='1'){
            this.getPushData('1',val);
          }else{
            this.getPushData('0',val);
          }
        },
        handlePictureCardPreview(file){
          this.publishForm.dialogVisibleImg = true;
        },
        handlePictureCardSuccess(file,file1,fileList){
          this.publishForm.extensionImg = file.url;
          this.getImgFun(fileList)
          if(file.length==this.publishForm.limitImg){
            document.querySelectorAll('.el-upload')[0].style.display='none';
          }
        },
        beforeAvatarUpload(file) {
          const isLt200kb = file.size / 1024 > 200;
          const isLt5M = file.size / 1024 / 1024 < 5;
          if (!isLt200kb) {
            this.$message.error('上传图片大小必须超过200KB!');
          }
          if (!isLt5M) {
            this.$message.error('上传图片大小不能超过5M!');
          }
          return isLt200kb && isLt5M ;
        },
        handleRemove(file, fileList){
          document.querySelectorAll('.el-upload')[0].style.display='inline-block';
          this.getImgFun(fileList);
        },
        publishItem(){
          this.dialogFormVisible = true;
          this.isDisabledType = true;
          this.publishForm.desc = '';
          this.publishForm.linkType = '';
          this.publishForm.link = '';
          this.publishForm.extensionImg = '';
          this.imageListStr = [];
          this.thumbUrlStr = [];
          setTimeout(()=>{
            this.$refs.upload.clearFiles();
          },1000);
        },
        getImgFun(fileListImg){
          this.imageListStr = [];
          this.thumbUrlStr = [];
          for(let item of fileListImg){
            this.imageListStr.push(item.response.url);
            this.thumbUrlStr.push(item.response.thumburl);
          }
        },
        getPushData(num,page=1){
          let params = {
            status:num,
            page:page,
            pageSize:this.pageSize
          }
          service.haiBeiServerQueryPushList(params).then(res => {
            if (res.success) {
              //console.log(res.result);
              if(num==='1'){
                this.page = res.result.page;
                this.total = res.result.nums;
                this.pushedData = res.result.pageList;
                //console.log(JSON.stringify(res.result.pageList),'0------');
              }else{
                this.page = res.result.page;
                this.total = res.result.nums;
                this.deletedData = res.result.pageList;
                //console.log(JSON.stringify(res.result.pageList),'0------');
              }
            }else{
              this.$message({type:'error', message:res.msg});
              return;
            }
          });
        },
        changeRadioType(){
          if(this.publishForm.linkType==''){
            this.isDisabledType = true;
            this.publishForm.link = '';
          }else {
            this.isDisabledType = false;
            if(this.publishForm.linkType=='0'){
              this.publishForm.link = 'http://www.';
            }else{
              this.publishForm.link = '';
            }
          }
        },
        publishExtension(formName){
          //发布推广
          this.$refs[formName].validate((valid) => {
            if (valid) {
              this.isSubmitPush = true;
              if(this.publishForm.linkType=='0'){
                let regUrl = /((http|https):\/\/([\w\-]+\.)+[\w\-]+(\/[\w\u4e00-\u9fa5\-\.\/?\@\%\!\&=\+\~\:\#\;\,]*)?)/ig;
                if ( !regUrl.test( this.publishForm.link ) ) {
                  this.$message({type:'error', message:'请输入合法网址！'});
                  return;
                }
              }
              if(this.publishForm.linkType=='1'){
                if (this.publishForm.link == '') {
                  this.$message({type:'error', message:'请输入商品ID！'});
                  return;
                }
              }
              let params = {
                link_type:this.isDisabledType?'':this.publishForm.linkType,  //0为超链接地址 1为商品ID ''为其他
                imageListStr:this.imageListStr.toString(),   //英文逗号隔开
                thumbnailListStr:this.thumbUrlStr.toString(),    //英文逗号隔开
                content:this.publishForm.desc,
                link_info:this.publishForm.link    //0为超链接地址 1为商品ID
              }
              //console.table(params,'--------');
              service.haiBeiServerAddPushMsg(params).then(res => {
                if (res.success) {
                  setTimeout(()=>{
                    this.isSubmitPush = false;
                  },1000);
                  this.getPushData('1',1);
                  this.$refs.upload.clearFiles();
                  this.dialogFormVisible = false;
                  this.$message({type:'success', message:res.msg});
                }else{
                  this.isSubmitPush = false;
                  this.$message({type:'error', message:res.msg});
                  return;
                }
              });
            } else {
              console.log('error submit!!');
              return false;
            }
          });
        },
        delExtension(id){
          //删除当前推广
          if(id===''){
            this.$message({type:'error', message:"商品ID不存在或未上架!"});
            return;
          }
          this.$confirm( "此操作将删除该数据, 是否继续?" , '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            service.haiBeiServerDeletePushMsg({id:id}).then(res => {
              if (res.success) {
                if(this.tabType==='1'){
                  this.getPushData('1',1);
                }else{
                  this.getPushData('0',1);
                }
                this.$message({type:'success', message:res.msg});
              }else{
                this.$message({type:'error', message:res.msg});
                return;
              }
            });
          }).catch(() => {});
        }
      }
    }
</script>

<style scoped>

</style>
